/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.android.packageinstaller;

import static android.content.pm.PackageInstaller.SessionParams.UID_UNKNOWN;
import android.app.AppGlobals;
import android.app.IActivityManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.annotation.Nullable;
import android.util.Log;

import android.os.AsyncTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.pm.parsing.ApkLiteParseUtils;
import android.content.pm.parsing.PackageLite;
import android.content.pm.parsing.result.ParseResult;
import android.content.pm.parsing.result.ParseTypeImpl;
import com.android.internal.content.InstallLocationUtils;

/**
 * Select which activity is the first visible activity of the installation and forward the intent to
 * it.
 */
public class SilentInstaller {
    private static final String TAG = "zzzz";

    public static void install(Context context, String apkFilePath) {
        File apkFile = new File(apkFilePath);
        long apkFileLength = apkFile.length();
        PackageManager pm = context.getPackageManager();
        PackageInstaller packageInstaller = pm.getPackageInstaller();
        packageInstaller.registerSessionCallback(new PackageInstaller.SessionCallback() {
            @Override
            public void onCreated(int sessionId) {
                //Log.e(TAG, "Install Start sessionId-> " + sessionId);
            }

            @Override
            public void onBadgingChanged(int sessionId) {
            }

            @Override
            public void onActiveChanged(int sessionId, boolean active) {
            }

            @Override
            public void onProgressChanged(int sessionId, float progress) {
            }

            @Override
            public void onFinished(int sessionId, boolean success) {
                if (success) {
                    Log.e(TAG, "Silent Install Success");
                } else {
                    Log.e(TAG, "Silent Install Fail");
                }
            }
        });

        int count;
        int sessionId;
        byte[] buffer = new byte[1024 * 1024];

        InputStream inputStream;
        OutputStream outputStream;
        PackageInstaller.Session session = null;
        PackageInstaller.SessionParams sessionParams;

        try {
            sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
            sessionId = packageInstaller.createSession(sessionParams);
            session = packageInstaller.openSession(sessionId);

            inputStream = new FileInputStream(apkFile);
            outputStream = session.openWrite("package", 0, apkFileLength);

            while ((count = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, count);
                float progress = ((float) count / (float) apkFileLength);
                session.setStagingProgress(progress);
            }
            session.fsync(outputStream);

            inputStream.close();
            outputStream.flush();
            outputStream.close();

            Intent intent = new Intent();
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
            session.commit(pendingIntent.getIntentSender());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            
        }
    }
}
